package com.wlstudy.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wlstudy.leyou.common.enums.ExceptionEnum;
import com.wlstudy.leyou.common.exception.LyException;
import com.wlstudy.leyou.upload.config.UploadProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

@Service
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 缩略图服务
     */
    @Autowired
    private ThumbImageConfig thumbImageConfig;

    @Autowired
    private UploadProperties props;

    public String uploadImage(MultipartFile file) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType();
            if (!props.getAllowTypes().contains(type)) {
                logger.info("上传失败，文件类型不匹配：{}", type);
                throw new LyException(ExceptionEnum.UPLOAD_FILE_TYPE_NOT_MATCH);
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                logger.info("上传失败，文件内容不符合要求");
                throw new LyException(ExceptionEnum.UPLOAD_FILE_CONTENT_NOT_MATCH);
            }
            // 2、将图片上传到FastDFS
            // 2.1、获取文件后缀名
            String extName = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 2.2、上传文件
            StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), extName, null);
            // 2.3、返回缩略图完整路径
            return props.getBaseUrl() + storePath.getGroup() + "/" + thumbImageConfig.getThumbImagePath(storePath.getPath());
        } catch (Exception e) {
            logger.error("文件上传失败！", e);
            throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }
}
